package jgl.vajra.kingkong.part.home.activity;

import android.text.TextUtils;
import android.view.View;

import androidx.recyclerview.widget.LinearLayoutManager;

import com.google.android.flexbox.FlexDirection;
import com.google.android.flexbox.FlexWrap;
import com.google.android.flexbox.FlexboxLayoutManager;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import jgl.vajra.kingkong.R;
import jgl.vajra.kingkong.bean.AddressBean;
import jgl.vajra.kingkong.bean.CityChoiceBean;
import jgl.vajra.kingkong.bean.OpenCityBean;
import jgl.vajra.kingkong.databinding.ActivityCityChoiceBinding;
import jgl.vajra.kingkong.event.CityChoiceEvent;
import jgl.vajra.kingkong.event.CitySearchEvent;
import jgl.vajra.kingkong.manager.IntentManager;
import jgl.vajra.kingkong.part.home.contract.CityChoiceContract;
import jgl.vajra.kingkong.part.home.viewModel.CityChoiceViewModel;
import jgl.vajra.kingkong.utils.RandomUtils;
import jgl.vajra.kingkong.widget.databindingadapter.BaseBindingItemPresenter;
import jgl.vajra.kingkong.widget.databindingadapter.SingleTypeBindingAdapter;
import jgl.vajra.kingkong.widget.manager.SPManager;
import jgl.vajra.kingkong.widget.mvvm.factory.CreateViewModel;
import jgl.vajra.kingkong.widget.mvvm.view.BaseMVVMActivity;
import jgl.vajra.kingkong.widget.retrofithelper.utils.AEACCoder;
import jgl.vajra.kingkong.widget.utils.ToastUtils;

@CreateViewModel(CityChoiceViewModel.class)
public class CityChoiceActivity extends BaseMVVMActivity<CityChoiceViewModel, ActivityCityChoiceBinding> implements CityChoiceContract.View, BaseBindingItemPresenter<CityChoiceBean> {

    private List<CityChoiceBean> cityChoiceBean = new ArrayList<>();
    private SingleTypeBindingAdapter adapter;
    private SingleTypeBindingAdapter provinceAdapter;
    private SingleTypeBindingAdapter cityAdapter;

    private OpenCityBean openCityBean;
    private int provincePosition;
    private String areaCode;
    private int provinceId = -1;//省Id
    private AddressBean currentPositioningData;

    @Override
    public int getLayoutId() {
        return R.layout.activity_city_choice;
    }

    @Override
    public void initView() {
        super.initView();
        mBinding.setView(this);

        mBinding.toolbar.setNavigationIcon(R.drawable.ic_left_arrow);
        mBinding.toolbar.setNavigationOnClickListener(view -> finish());

        //当前位置信息
        currentPositioningData = SPManager.HomeData.getAddressData();

        if (currentPositioningData != null && !TextUtils.isEmpty(currentPositioningData.locality)) {
            mBinding.tvCurrentPositioning.setText(currentPositioningData.locality.replace("市", ""));
        }

        //上一次选择的
        CityChoiceBean selectLocationData = SPManager.HomeData.getSelectLocationData();
        if (selectLocationData != null && !TextUtils.isEmpty(selectLocationData.abbreviation)) {
            mBinding.tvSelectLocation.setText(selectLocationData.abbreviation);
        } else {
            if (currentPositioningData != null && !TextUtils.isEmpty(currentPositioningData.locality)) {
                mBinding.tvSelectLocation.setText(currentPositioningData.locality.replace("市", ""));
            }
        }

        cityChoiceBean.clear();
        List<CityChoiceBean> latelyAddressInfo = SPManager.HomeData.getLatelyAddressInfo(this);
        cityChoiceBean.addAll(latelyAddressInfo);
        if (latelyAddressInfo.size() == 0) {
            mBinding.tvTitle.setVisibility(View.GONE);
        } else {
            mBinding.tvTitle.setVisibility(View.VISIBLE);
        }

        // 不可嵌套滑动
        mBinding.recyclerView.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerView.setFocusableInTouchMode(false);

        FlexboxLayoutManager flManager = new FlexboxLayoutManager(this);
        //
        flManager.setFlexWrap(FlexWrap.WRAP);
        //设置主轴的方向
        flManager.setFlexDirection(FlexDirection.ROW);
        //设置布局管理器
        mBinding.recyclerView.setLayoutManager(flManager);
        adapter = new SingleTypeBindingAdapter(this, cityChoiceBean, R.layout.item_city_choice);
        mBinding.recyclerView.setAdapter(adapter);
        adapter.setItemPresenter(this);


        // 不可嵌套滑动
        mBinding.recyclerViewProvince.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerViewProvince.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerViewProvince.setLayoutManager(new LinearLayoutManager(this));
        provinceAdapter = new SingleTypeBindingAdapter(this, null, R.layout.item_receiving_area_province);
        mBinding.recyclerViewProvince.setAdapter(provinceAdapter);
        provinceAdapter.setItemPresenter(this);

        // 不可嵌套滑动
        mBinding.recyclerViewCity.setNestedScrollingEnabled(false);
        // 取消head 的 recycleView的焦点
        mBinding.recyclerViewCity.setFocusableInTouchMode(false);
        //设置布局管理器
        mBinding.recyclerViewCity.setLayoutManager(new LinearLayoutManager(this));
        cityAdapter = new SingleTypeBindingAdapter(this, null, R.layout.item_receiving_area);
        mBinding.recyclerViewCity.setAdapter(cityAdapter);
        cityAdapter.setItemPresenter(this);

        requestNetData();
    }

    private void requestNetData() {
        Map<String, Object> map = new HashMap<>();
        map.put("Authorization", AEACCoder.encrypt(RandomUtils.getRandom()));
        //mViewModel.getAreaInfoData(map);

        mViewModel.getOpenCityData(map);
    }

    @Override
    public void initData() {
        super.initData();
    }

    //搜索
    @Override
    public void onSearch() {
        IntentManager.toCitySearchActivity(this);
    }

    //点击当前定位
    @Override
    public void onCurrentPositioning() {
        if (currentPositioningData != null && !TextUtils.isEmpty(currentPositioningData.locality)) {

        } else {
            ToastUtils.showShort("定位失败");
        }
    }

    @Override
    public void returnAreaInfoBean(List<CityChoiceBean> cityChoiceBean) {
        adapter.refresh(cityChoiceBean);
    }

    //省份
    @Override
    public void onChoiceProvince(int position, OpenCityBean.ProvinceListBean itemData) {
        if (itemData.isClick) return;
        for (int i = 0; i < openCityBean.provinceList.size(); i++) {
            openCityBean.provinceList.get(i).isClick = false;
            for (int j = 0; j < openCityBean.provinceList.get(i).cityList.size(); j++) {
                openCityBean.provinceList.get(i).cityList.get(j).isClick = false;
            }
        }

        provincePosition = position;
        openCityBean.provinceList.get(position).isClick = true;
        provinceId = itemData.id;
        provinceAdapter.refresh();
        cityAdapter.refresh(itemData.cityList);
    }

    @Override
    public void onChoiceArea(int position, OpenCityBean.ProvinceListBean.CityListBean itemData) {
        if (provinceId == -1) {
            ToastUtils.showShort("请先选择省份");
            return;
        }

        if (itemData.isClick) return;
        for (int i = 0; i < openCityBean.provinceList.get(provincePosition).cityList.size(); i++) {
            openCityBean.provinceList.get(provincePosition).cityList.get(i).isClick = false;
        }
        areaCode = itemData.areaCode;
        openCityBean.provinceList.get(provincePosition).cityList.get(position).isClick = true;
        cityAdapter.refresh();

        CityChoiceBean bean = new CityChoiceBean();
        bean.areaCode = itemData.areaCode;
        bean.abbreviation = itemData.name;
        bean.longitude = itemData.longitude;
        bean.latitude = itemData.latitude;

        List<CityChoiceBean> latelyAddressInfo = SPManager.HomeData.getLatelyAddressInfo(this);

        for (int i = 0; i < latelyAddressInfo.size(); i++) {
            if (i > 9) {
                latelyAddressInfo.remove(i);
            }

        }
        for (int i = 0; i < latelyAddressInfo.size(); i++) {
            if (itemData.name.equals(latelyAddressInfo.get(i).abbreviation)) {
                latelyAddressInfo.remove(i);
            }

        }
        latelyAddressInfo.add(0, bean);

        SPManager.HomeData.saveLatelyAddressInfo(this, latelyAddressInfo);

        EventBus.getDefault().post(new CityChoiceEvent(bean));
        finish();
    }

    @Override
    public void returnOpenCityData(OpenCityBean openCityBean) {
        this.openCityBean = openCityBean;

        provinceAdapter.refresh(openCityBean.provinceList);
        cityAdapter.refresh(openCityBean.provinceList.get(0).cityList);
    }

    @Override
    public void onItemClick(int position, CityChoiceBean itemData) {
        EventBus.getDefault().post(new CityChoiceEvent(itemData));
        finish();
    }

    @Override
    protected boolean isRegisterEvent() {
        return true;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onCitySearchEvent(CitySearchEvent event) {
        EventBus.getDefault().post(new CityChoiceEvent(event.itemData));
        finish();
    }
}
